// pages/Detail/detail.js
const WxParse = require('../Common/wxParse/wxParse.js');
const Controller = require('../controllers/controllers.js').controller;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 轮播图当前索引
        currentIndex: 0,
        // 折叠面板当前的数据
        activeNames: [],
        infoList:[],
        //商品id
        id: '',
        visible:false,
        info: {},
        attrIds:[],
        verification: [],
        cartNum: 0,
        list: [],
        //库存
        stock: 0,
        discountPrice: '',
        loading:false
        
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
       
       if(options.scene){
         let scene=decodeURIComponent(options.scene)

         let arr  = scene.split('&')

         let obj={}

        for(let item of arr){
          item=item.split('=')
          obj[item[0]]=item[1]
        }
       
        this.setData(obj)
       
       }
       else{
           
            this.setData({
                id: options.id,
                parentid:options.parentid||wx.getStorageSync('shareparentId')
            })
        }
        this.getInfo()
        this.getList()
            //  获取当前页面路径
    },
    //格式化富文本
    formatRichText(html) {
        if (html) {
            let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
                match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
                match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
                match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
                return match;
            });
            newContent = newContent.replace(/<table[^>]*>/gi, function(match, capture) {
                match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
                match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
                match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
                return match;
            });
            newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
                match = match.replace(/width:[^;]+;/gi, 'max-width:100%;vertical-align:middle;')
                return match;
            });
            // newContent = newContent.replace(/<br[^>]*\/>/gi, '');
            newContent = newContent.replace(/\<img/gi,
                '<img style="max-width:100%;vertical-align:middle;"');
            return newContent;
        }
    },

    //查看尺码
    goSize() {
        wx.navigateTo({
            url: `/pages/Detail/size?id=${this.data.id}`,
        })
    },

    //选择规格
async select(e) {
   
        let type = e.currentTarget.dataset.type
        let index = e.currentTarget.dataset.index
        let stock = e.currentTarget.dataset.stock
        let defaultval = e.currentTarget.dataset.defaultval
        let info = this.data.info

       
        if (!stock) {
            return
        }
       let isSelect= info.goodsSpecList[type].attributeList[index].select
       
       if(isSelect&&!defaultval){
          return
       }
    
        let maxLen=info.goodsSpecList.length-1
         
       
        if(!this.stopSelect(type)){
            return false
        }
        info.goodsSpecList[type].attributeList.forEach((ite,i)=>{
        
            if(i===index){
                ite.select=true
            }else{
                ite.select=false
            }

        }) 

        
      
          let goodsId=info.id
        // 获取的name(选中)
          let desc=[]
        
        
          info.goodsSpecList.forEach((item,index)=>{
              if(index<=type){
                item.attributeList.forEach((ite,i)=>{
                    if(ite.select){
                        desc.push( item.name+':'+ite.name)
                    }
                })
              }     
          })
       let copydesc=JSON.parse(JSON.stringify(desc)) 
        desc=desc.join(',')
    if(type<maxLen){
       let res  =  await  Controller.getCategoryStock({goodsId,desc})
               let arr=res.data.baseData
               let hasFull=res.data.hasFull

              for(let index=0;index<=maxLen;index++){
            
              if(index===(type+1)){
                (hasFull&&!arr.includes('全套'))?arr.unshift('全套'):''
                this.data.cacheSpec[index]=arr
             }
             if(index>(type+1)){
                this.data.cacheSpec[index]=''
             }

             }
          

               this.CheckStock(type)
               info.discountPrice=0

                 this.setData({
                    attrIds:[]
               })
    }         
    let discountPrice=0
    let res1={}
  
      if(copydesc.includes('款式:全套')){
   
       let arr =info.goodsSpecList[1].attributeList

       for(let v of arr){
        if(v.name!=='全套'){
            copydesc[1]=`款式:${v.name}`
            desc=copydesc.join(',')
            res1=await Controller.getCategoryPrice({goodsId,desc})
            discountPrice+=res1.data.baseData

        }
       }
          
          
      }else{
      res1 =  await Controller.getCategoryPrice({goodsId,desc})
        discountPrice=res1.data.baseData
      } 

    if(type===maxLen){
        this.toTalPrice()
    }
    
    if(type!=0){

        this.setData({
            info,
            'info.discountPrice':discountPrice
       })

    }else{
        this.defaultSelect(1)
    }
    

         

        
     
        
        

       
       
        
      
        
        
        // let attrIds = []
       
      
      
    },
   
    //计算总价
    toTalPrice(){
      let info=this.data.info
    //所有库存信息
      let specAttributePriceList=info.specAttributePriceList
     
     let attrIds=[]
     let arr=[]
     let ids=[]
      info.goodsSpecList.forEach(item=>{
       item.attributeList.forEach((ite,i,owner)=>{
           if(ite.select){
            if(ite.name==='全套'){
              
               for(let v of owner){
                   if(v.name!=='全套'){
                     ids.push(v.id)
                   }
               }
            }else{
                arr.push(ite.id)
            } 

           }
           
       })

      })
  
      let str=''
      
     if(ids.length>0){
       
      for(let v of ids){
       attrIds.push(arr[0]+','+v+','+arr[1]+','+arr[2]) 
      }
    
     }else{
        attrIds.push(arr.join(','))
     }
     
     console.log('attrIds==>',attrIds)

     let discountPrice=0
     for(let v of attrIds){
    
     for(let s of specAttributePriceList){
        if(s.attrIds===v){
            discountPrice+=s.discountPrice
            break;
        } 

     }
   
    }
    this.setData({
        attrIds
    })
     console.log('discountPrice',discountPrice)
    return discountPrice
     


     
      
    },
    //遍历售罄
    
    CheckStock(type){
     let  info=this.data.info
    // type的最大值 
     let maxLen=info.goodsSpecList.length-1
    
    if(type>=maxLen){
        return
    }
     
     info.goodsSpecList.forEach((item,index)=>{

    //   
         
       //重置select
       
       
         item.attributeList.forEach((ite,i)=>{
        ite.stock=this.hasStock(index,ite.name)
            if(index>type){
            ite.select=false
            }
         })
  
      
      
        
     })
     
  
    },
    //判断是否可以选择
    stopSelect(type){
        let info=this.data.info
        let titles=info.goodsSpecList.map(v=>{
            return v.name
        })
        let  notSelect=0
      
       for(let index=0;index<info.goodsSpecList.length;index++){
           let item=info.goodsSpecList[index]
            if(type>index){
              let isSelect = item.attributeList.some(ite=>{
                    return ite.select
               })
               if(!isSelect){
                  notSelect=index
                  break
               }
            }
        }
      
        if(notSelect!==0){
             wx.showToast({
                title:`请先选择${titles[notSelect]}`,
                icon:'none'
              })
            return false
        }else{
           return  true
        }
    
      
        
    
    },
    
    
    //获取商品详情
    getInfo() {
        Controller.goodsdetail({
            goodsId: this.data.id
        }).then(res => {
            let info = res.data.baseData
         
        
            if (info.imgUrls.indexOf(',') != '-1') {
                info.imgList = info.imgUrls.split(',')
            } else {
                info.imgList = [info.imgUrls]
            }
            // let verification = info.specAttributePriceList

            //为款式添加全套



            // 初始化select以及库存
           //版本库存
            let  spec1StockAttrs=info.spec1StockAttrs||[]
          //款式库存
            let  spec2StockAttrs=info.spec2StockAttrs||[]

            let spec3StockAttrs=info.spec3StockAttrs||[]


            if(info.hasFull){
                spec2StockAttrs.unshift('全套')

              
            }
            info.goodsSpecList.forEach((item,index)=>{
                if(item.description==='款式'){
                    let id =item.attributeList.map((ite,i)=>ite.id)
                    let titles=item.attributeList.map(ite=>ite.name)
                  if(!titles.includes('全套')){
                       id=id.join(',')
                       let obj={image: "", name: "全套", id}
                       item.attributeList.unshift(obj)
                  }
                  
                   }
            })

        


        let cacheSpec=[spec1StockAttrs,spec2StockAttrs,spec3StockAttrs]
           
        console.log('cacheSpec',cacheSpec)
        
        cacheSpec=this.sortRules(cacheSpec,info.goodsSpecList)

        console.log('cacheSpec',cacheSpec)
         
        

           

        // 当前选择的索引值

            let  currentIndex=-1

           
           
            this.data.cacheSpec=cacheSpec
          info.goodsSpecList.forEach((item,index)=>{
           

           item.attributeList.forEach((ite,i)=>{
               
            if(index<2){
             
              if(ite.name===cacheSpec[index][0]){
                  ite.select=true

                  this.data.currentIndex=currentIndex=index
            
              }else{
                  ite.select=false
             }
            }else{
                ite.select=false
            }
            ite.stock=this.hasStock(index,ite.name)
            
           })
           
            
          })

    
            
            this.setData({
                info,
                cacheSpec,
                loading:true
            },()=>{
       

             this.defaultSelect(1)

            
               
            })
            if(info.subTitle){
                info.subTitle=info.subTitle.replace(/\n/g,'<p style="height:0px;margin:0px;"></p>')

                WxParse.wxParse('subTitle', 'html', this.formatRichText(info.subTitle), this, 5);

            }

            if (info.content) {
                WxParse.wxParse('content', 'html', this.formatRichText(info.content), this, 5);
            }
            if (info.afterSaleInfo) {
                WxParse.wxParse('afterSaleInfo', 'html', this.formatRichText(info.afterSaleInfo), this, 5);
            }
            if (info.washInfo) {
                WxParse.wxParse('washInfo', 'html', this.formatRichText(info.washInfo), this, 5);
            }
        })
    },
    
    defaultSelect(type){

        let info=this.data.info

        
        let cacheSpec=this.data.cacheSpec[type]||[]
     
        let   index=info.goodsSpecList[type].attributeList.findIndex(ite=>cacheSpec.includes(ite.name))
    
        
    

        let e={currentTarget:{dataset:{
            type,
            index,
            stock:true,
            defaultval:true
        }}}
     
       
      

        this.select(e)


    },

    hasStock(type,target){
    

    let item=this.data.cacheSpec[type]
    
     if(item){

        if(item.indexOf(target)>-1){
            return true
          }else{
            return false
          }
     }else{
         return true
     }
      
     },


     sortRules(cacheSpec,goodsSpecList){
          goodsSpecList=JSON.parse(JSON.stringify(goodsSpecList)) 
        let data =goodsSpecList.map((item,index)=>{
        
            if(index<cacheSpec.length){
               let arr=[]
                 
               item.attributeList.map((ite,i)=>{
               
                 if(cacheSpec[index].includes(ite.name)){
                    console.log('ite.name',ite.name)
                    arr.push(ite.name)
                 }
                     
                   
              })

              return arr
    
            }else{
                return ''
            }
           
    
            })
    
    
          return data
     },

    
    //获取商品列表
    getList() {
        Controller.goodslist({
            isRecommend: 1,
            page: 1,
        }).then(res => {
            let list = res.data.baseData.list
            this.setData({
                list
            })
        })
    },
    //跳转详情
    goDetail(e) {
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: `/pages/Detail/detail?id=${id}`,
        })
    },
    //获取购物车数量
    geCartcount() {
        Controller.cartcount().then(res => {
            this.setData({
                cartNum: res.data.baseData
            })
        })
    },
    //页面跳转
    goPage(e) {
        let url = e.currentTarget.dataset.url
        wx.reLaunch({
            url
        })
    },
    //下单
    placeOrder() {

        let info = this.data.info
        //所有库存信息
     let specAttributePriceList=info.specAttributePriceList
       let specs = []
       let attrIds = this.data.attrIds
     
       
       if (attrIds.length===0) {
           wx.showToast({
               title: '请先选择规格',
               icon: 'none'
           })
           return
       }
       let goodsSpecAttributePriceIds=[]
       for(let index=0;index<attrIds.length;index++){
    
        let item=attrIds[index]

      let indexId=specAttributePriceList.findIndex(v=>v.attrIds===item)

       goodsSpecAttributePriceIds.push(specAttributePriceList[indexId].id)
       
       }
        
       goodsSpecAttributePriceIds=goodsSpecAttributePriceIds.join(',')
        wx.navigateTo({
            url: `/pages/Pay/pay?parentid=${this.data.parentid}&goodsId=${this.data.id}&goodsSpecAttributePriceIds=${goodsSpecAttributePriceIds}&type=goods`
        })
    },
    //加入购物车
    joinCart() {
        let info = this.data.info
         //所有库存信息
      let specAttributePriceList=info.specAttributePriceList
        let specs = []
        let attrIds = this.data.attrIds
      
        
        if (attrIds.length===0) {
            wx.showToast({
                title: '请先选择规格',
                icon: 'none'
            })
            return
        }

        attrIds.forEach((item,index)=>{

            let name=''
            let arr=[]
            let  itemArr= item.split(',')
            console.log('itemArr',itemArr)
            itemArr.forEach((ite,i)=>{
            
                
                let specItem=info.goodsSpecList[i]
                console.log('specItem',specItem)
                
                specItem.attributeList.forEach((t,c)=>{
                 console.log('t.id',t.id,ite)
                  if(t.id===Number(ite)){
                    arr.push(specItem.name + ':' + t.name)
                  }

                })

            })
          
          specs.push(arr.join(','))
        
        })
        console.log('specs',specs)
        
        

      for(let index=0;index<attrIds.length;index++){
          let item=attrIds[index]

          console.log('item==>',item)

        let indexId=specAttributePriceList.findIndex(v=>v.attrIds===item)

        let goodsSpecAttributePriceId=specAttributePriceList[indexId].id


        
        Controller.addOrUpdate({
            goodsId: this.data.id,
            specs: specs[index],
            attrIds: attrIds[index],
            amount: 1,
            goodsSpecAttributePriceId,
            type: 1,
        }).then(res => {
            wx.showToast({
                title: '加入成功',
                icon: 'none'
            })
            this.geCartcount()
        })
        
      }
     
        
       

    },
    change(e) {
        let current = e.detail.current
        console.log('e==>', e)
        this.setData({
            currentIndex: current
        })
    },
    handleCollapse(event) {
        this.setData({
            activeNames: event.detail,
        });
    },
    handleToggle(e){

    if(e.currentTarget.dataset.visible){
        this.setData({
            visible:true
        })
    }else{

        this.setData({
            visible:e.detail
        })

    }

    
      
    },
  
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },
    //触发分享接口
   

    onShareAppMessage() {
        let id = this.data.id
        let title = this.data.info.title
        let path = getApp().getCurrentPageUrlWithArgs()
        console.log('path',path)
        return {
            title,
            path,
            success:function(res){
             console.log("onShareAppMessage",res)
            },
            fail(err) {
              console.log("onShareAppMessage",err)
            }
            
        }
    },


    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        this.geCartcount()
       
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    }


})